<template>
  <div class="member">
    <div class="columns">
      <div class="column is-one-quarter">
        <el-card shadow="never">
          <div slot="header" class="has-text-centered">
            <el-avatar :size="64" :src="`https://cn.gravatar.com/avatar/${topicUser.id}?s=164&d=monsterid`" />
            <p class="mt-3">{{ topicUser.alias || topicUser.username }}</p>
          </div>
          <div>
            <p class="content">积分：<code>{{ topicUser.score }}</code></p>
            <p class="content">入驻：{{ dayjs(topicUser.createTime).format("YYYY/MM/DD HH:MM:ss") }}</p>
            <p class="content">简介：{{ topicUser.bio }}</p>
            <el-button @click="showChatPanel">聊天</el-button>
            <el-dialog title="我的信息" :visible.sync="chatPanelVisible" width="30%" @close="closeChatPanel">
              <!-- 用户列表 -->
              <el-select v-model="toUser" filterable placeholder="选择联系人">
                <el-option v-for="user in userList" :key="user.id" :label="user.username" :value="user.id">
                </el-option>
              </el-select>
              <!-- 消息记录 -->
              <MessageLists :messageList="messageList" :user="user" />
            </el-dialog>
          </div>
          <div class="ml-2" style="display: flex; flex-wrap: wrap; overflow: hidden;"> <!-- 粉丝列表 -->
            <div v-for="(follows, index) in follow" :key="index" style="margin-left: 20px;">
              <el-avatar :size="65" :src="`https://cn.gravatar.com/avatar/${follow.id}?s=164&d=monsterid`" />
              <p class="mt-3">{{ follows.alias || follows.username }}</p>
            </div>
          </div>
        </el-card>
      </div>

      <div class="column">
        <!--用户发布的话题-->
        <el-card class="box-card content" shadow="never">
          <div slot="header" class="has-text-weight-bold">
            <span>话题</span>
          </div>

          <div v-if="topics.length === 0">
            暂无话题
          </div>

          <div v-else class="topicUser-info">
            <article v-for="(item, index) in topics" :key="index" class="media">
              <div class="media-content">
                <div class="content ellipsis is-ellipsis-1">
                  <el-tooltip class="item" effect="dark" :content="item.title" placement="top">
                    <router-link :to="{ name: 'post-detail', params: { id: item.id } }">
                      {{ item.title }}
                    </router-link>
                  </el-tooltip>
                </div>
                <nav class="level has-text-grey is-size-7">
                  <div class="level-left">
                    <span class="mr-1">
                      发布于:{{ dayjs(item.createTime).format("YYYY/MM/DD HH:mm:ss") }}
                    </span>
                  </div>
                </nav>
              </div>
              <div v-if="token" class="media-right">
                <div v-if="topicUser.username === user.username" class="level">
                  <div class="level-item mr-1">
                    <router-link :to="{ name: 'topic-edit', params: { id: item.id } }">
                      <span class="tag is-warning">编辑</span>
                    </router-link>
                  </div>
                  <div class="level-item">
                    <a @click="handleDelete(item.id)">
                      <span class="tag is-danger">删除</span>
                    </a>
                  </div>
                </div>
              </div>
            </article>
          </div>

          <!--分页-->
          <pagination v-show="page.total > 0" :limit.sync="page.size" :page.sync="page.current" :total="page.total"
            class="mt-5" @pagination="fetchUserById" />
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { getInfoByName } from '@/api/user'
import pagination from '@/components/Pagination/index'
import { mapGetters } from 'vuex'
import { deleteTopic } from '@/api/post'
import { getFollowList } from '@/api/follow'
import MessageLists from '@/components/Message/MessageList.vue'
import axios from 'axios'

export default {
  name: 'Profile',
  components: { pagination, MessageLists },
  data() {
    return {
      follow: [],
      topicUser: {},
      userList: [],     // 用户列表
      messageList: [],  // 消息记录
      toUser: '',       // 接收用户id
      messageContent: '', // 消息内容
      chatPanelVisible: false,
      topics: {},
      page: {
        current: 1,
        size: 5,
        total: 0
      }
    }
  },
  computed: {
    ...mapGetters(['token', 'user'])
  },
  created() {
    this.fetchUserById(),
      axios.get('/ums/user/lists').then(res => {
        this.userList = res.data
      })
  },
  methods: {
    fetchUserById() {
      getInfoByName(this.$route.params.username, this.page.current, this.page.size).then((res) => {
        const { data } = res
        this.topicUser = data.user
        this.page.current = data.topics.current
        this.page.size = data.topics.size
        this.page.total = data.topics.total
        this.topics = data.topics.records
        this.fetchFollowList()
      })
    },
     show() {
      axios
          .get(`/api/messages/${this.$store.getters.user.id}`)
          .then((response) => {
            console.log(this.$store);
            this.messages = response.data;
            this.dialogVisible = true;
            console.log(this.messages);
          })
          .catch((error) => {
            console.log(error);
          });
    },
    getMsgList() {
      axios.get(`/api/messages/${this.$store.getters.user.id}`).then(res => {
        this.messageList = res.data
      })
    },
    fetchFollowList() {
      getFollowList(this.topicUser.id).then((response) => {
        this.follow = response.data;
        console.log(response.data);
      })
    },
    showChatPanel() {
      axios.get(`/api/messages/list?fromUser=${this.user.id}&toUser=${this.toUser}`).then(res => {
        this.messageList = res.data
      })
      this.chatPanelVisible = true
    },
    handleDelete(id) {
      deleteTopic(id).then(value => {
        const { code, message } = value
        alert(message)

        if (code === 200) {
          setTimeout(() => {
            this.$router.push({ path: '/' })
          }, 500)
        }
      })
    },
    sendMessage() {   // 发送消息
      const message = {
        fromUser: this.user.id,
        toUser: this.toUser,
        content: this.messageContent
      }
      axios.post('/api/messages/send', message).then(res => {
        socket.emit('message', {
          toUser: this.toUser,
          content: `您有一条新消息,来自${this.user.username}`
        })
        this.messageContent = ''  // 清空
        const msg = {
          fromUser: this.user.id,
          content: this.messageContent
        }
        this.messageList.unshift(msg)
      })
    },
    closeChatPanel() {
      this.toUser = ''
      this.messageList = []
    }

  }
}
</script>

<style scoped></style>
